package tools;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 密码加密工具类
 * 用于生成和验证BCrypt密码哈希值
 * 
 * @author AI Assistant
 * @date 2024-01-01
 */
public class PasswordEncoder {
    
    /**
     * BCrypt密码编码器实例
     */
    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    
    /**
     * 加密明文密码
     * 
     * @param rawPassword 明文密码
     * @return BCrypt哈希值
     */
    public static String encode(String rawPassword) {
        return encoder.encode(rawPassword);
    }
    
    /**
     * 验证密码是否匹配
     * 
     * @param rawPassword 明文密码
     * @param encodedPassword 已加密的密码哈希
     * @return 是否匹配
     */
    public static boolean matches(String rawPassword, String encodedPassword) {
        return encoder.matches(rawPassword, encodedPassword);
    }
    
    /**
     * 主方法 - 用于测试和生成密码哈希
     * 
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        // 如果有命令行参数，使用第一个参数作为密码
        String password = args.length > 0 ? args[0] : "admin123";
        
        System.out.println("=== BCrypt密码加密工具 ===");
        System.out.println("明文密码: " + password);
        
        // 生成哈希值
        String hash = encode(password);
        System.out.println("BCrypt哈希: " + hash);
        
        // 验证哈希值
        boolean isValid = matches(password, hash);
        System.out.println("验证结果: " + (isValid ? "✅ 匹配" : "❌ 不匹配"));
        
        System.out.println("\n=== 常用密码哈希值 ===");
        
        // 生成常用密码的哈希值
        String[] commonPasswords = {"admin123", "test123", "123456", "password"};
        
        for (String pwd : commonPasswords) {
            String pwdHash = encode(pwd);
            System.out.printf("%-10s -> %s%n", pwd, pwdHash);
        }
        
        System.out.println("\n=== SQL更新语句 ===");
        System.out.println("-- 更新admin用户密码");
        System.out.printf("UPDATE sys_user SET password = '%s' WHERE username = 'admin';%n", 
                         encode("admin123"));
        
        System.out.println("-- 更新test用户密码");
        System.out.printf("UPDATE sys_user SET password = '%s' WHERE username = 'test';%n", 
                         encode("test123"));
    }
}